<template>
  <div id="app" :class="currentTheme">
    <!-- 背景图层 -->
    <div class="background-layer"></div>

    <!-- 登录状态显示布局 -->
    <template v-if="userStore.isLoggedIn">
      <div class="page-container">
        <!-- 顶部Header -->
        <el-header class="header-container">
          <Header 
            :is-collapsed="isSidebarCollapsed"
            @toggle-sidebar="safeToggleSidebar"
            @change-theme="changeTheme"
            @logout="handleLogout"
          />
        </el-header>

        <div class="content-container">
          <!-- 左侧Sidebar -->
          <div class="sidebar" :class="{ 'collapsed': isSidebarCollapsed }">
            <Sidebar :is-collapsed="isSidebarCollapsed" />
          </div>

          <!-- 右侧主内容区 -->
          <div class="main-content">
            <!-- 标签页区域 -->
            <div class="tabs-wrapper">
              <el-tabs
                v-model="activeTab"
                type="card"
                closable
                @tab-remove="removeTab"
                @tab-click="clickTab"
                :animated="true"
              >
                <el-tab-pane
                  v-for="item in tabs"
                  :key="item.path"
                  :name="item.path"
                  :closable="item.meta.closable"
                >
                  <template #label>
                    <span>{{ item.meta.title }}</span>
                  </template>
                </el-tab-pane>
              </el-tabs>
              <el-dropdown @command="handleTabCommand">
                <el-icon class="more-btn"><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="closeCurrent">关闭当前</el-dropdown-item>
                    <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
                    <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <!-- 路由内容 -->
            <div class="router-content">
              <router-view v-slot="{ Component }">
                <keep-alive>
                  <component :is="Component" class="router-view-container" />
                </keep-alive>
              </router-view>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 未登录状态 -->
    <router-view v-else />
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import Header from '@/components/layout/Header.vue'
import { useUserStore } from '@/stores/userStore'
import { autoFixStyles } from '@/utils/styleFix'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const isLoading = ref(false)

// 侧边栏收起状态
const isSidebarCollapsed = ref(false)







// 极简的切换方法
const safeToggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}



// 标签页数据
const tabs = ref([
  {
    path: '/home',
    meta: {
      title: '首页',
      closable: false
    }
  }
])

// 当前激活标签
const activeTab = ref('/home')

// 主题定义
const themes = {
  atour: {
    name: "深海蓝调",
    primary: "#1a365d",
    secondary: "#c9a063",
    accent: "#4a6584",
    background: "#f5f2ea",
    text: "#333333",
    headerBg: "linear-gradient(135deg, #1a365d 0%, #2c5282 100%)",
    sidebarBg: "linear-gradient(180deg, #1a365d 0%, #2a4365 100%)",
    loginBg: "linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('/src/assets/atour-bg.jpg')",
    pageHeaderBg: "rgba(255, 255, 255, 0.95)"
  },
  intercity: {
    name: "春意盎然",
    primary: "#006747",
    secondary: "#d4af37",
    accent: "#8db600",
    background: "#f0f4f8",
    text: "#2d3748",
    headerBg: "linear-gradient(135deg, #006747 0%, #008060 100%)",
    sidebarBg: "linear-gradient(180deg, #006747 0%, #004d38 100%)",
    loginBg: "linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('/src/assets/intercity-bg.jpg')",
    pageHeaderBg: "rgba(255, 255, 255, 0.95)"
  },
  marriott: {
    name: "暖阳金秋",
    primary: "#ac915b",
    secondary: "#8c1515",
    accent: "#d4b483",
    background: "#f8f5f0",
    text: "#3c3c3c",
    headerBg: "linear-gradient(135deg, #8c1515 0%, #ac915b 100%)",
    sidebarBg: "linear-gradient(180deg, #8c1515 0%, #6d0f0f 100%)",
    loginBg: "linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('/src/assets/marriott-bg.jpg')",
    pageHeaderBg: "rgba(255, 255, 255, 0.95)"
  }
};

// 主题相关变量
const currentTheme = ref('atour')



// 应用主题
const applyTheme = (themeKey) => {
  const theme = themes[themeKey];
  if (!theme) return;
  
  const root = document.documentElement;
  
  root.style.setProperty('--primary-color', theme.primary);
  root.style.setProperty('--secondary-color', theme.secondary);
  root.style.setProperty('--accent-color', theme.accent);
  root.style.setProperty('--background-color', theme.background);
  root.style.setProperty('--text-color', theme.text);
  root.style.setProperty('--header-bg', theme.headerBg);
  root.style.setProperty('--sidebar-bg', theme.sidebarBg);
  root.style.setProperty('--login-bg', theme.loginBg);
  root.style.setProperty('--page-header-bg', theme.pageHeaderBg);
  
  // 保存主题到本地存储
  localStorage.setItem('selectedTheme', themeKey);
}

// 切换主题
const changeTheme = (themeKey) => {
  currentTheme.value = themeKey;
  applyTheme(themeKey);
  
  // 修复样式
  nextTick(() => {
    autoFixStyles()
  })
}



// 初始化主题
onMounted(() => {
  // 加载主题
  const savedTheme = localStorage.getItem('selectedTheme');
  if (savedTheme && themes[savedTheme]) {
    currentTheme.value = savedTheme;
  }
  applyTheme(currentTheme.value);
  
  // 侧边栏状态初始化（默认展开）
  isSidebarCollapsed.value = false
  

  
  // 添加活动监听器
  window.addEventListener('mousemove', handleUserActivity)
  window.addEventListener('keydown', handleUserActivity)
  window.addEventListener('click', handleUserActivity)
  window.addEventListener('scroll', handleUserActivity)
  
  // 初始计时器
  if (userStore.isLoggedIn) {
    userStore.updateLastActivityTime()
    resetActivityTimer()
  }
  
  // 添加状态恢复按钮（生产环境可隐藏）
  if (import.meta.env.DEV) {
    const recoveryBtn = document.createElement('button')
    recoveryBtn.textContent = '重置浏览器状态'
    recoveryBtn.style.position = 'fixed'
    recoveryBtn.style.bottom = '10px'
    recoveryBtn.style.right = '10px'
    recoveryBtn.style.zIndex = '9999'
    recoveryBtn.style.padding = '8px 16px'
    recoveryBtn.style.background = '#f56c6c'
    recoveryBtn.style.color = 'white'
    recoveryBtn.style.borderRadius = '4px'
    recoveryBtn.style.border = 'none'
    recoveryBtn.style.cursor = 'pointer'
    recoveryBtn.onclick = () => {
      localStorage.clear()
      sessionStorage.clear()
      location.reload()
    }
    document.body.appendChild(recoveryBtn)
  }
});

// 清理
onUnmounted(() => {
  window.removeEventListener('mousemove', handleUserActivity)
  window.removeEventListener('keydown', handleUserActivity)
  window.removeEventListener('click', handleUserActivity)
  window.removeEventListener('scroll', handleUserActivity)

  
  if (activityTimer) clearTimeout(activityTimer)
})

// ========== 添加无操作检测逻辑 ==========
const INACTIVITY_TIMEOUT = 30 * 60 * 1000 // 30分钟
let activityTimer = null

// 重置活动计时器
const resetActivityTimer = () => {
  if (activityTimer) clearTimeout(activityTimer)
  
  // 设置新的计时器
  activityTimer = setTimeout(() => {
    // 用户未操作超时处理
    if (userStore.isLoggedIn) {
      ElMessage.warning('由于长时间未操作，系统已自动登出')
      handleLogout()
    }
  }, INACTIVITY_TIMEOUT)
}

// 用户活动处理器 - 简化版本
const handleUserActivity = () => {
  // 只在用户已登录时更新活动时间
  if (userStore.isLoggedIn) {
    userStore.updateLastActivityTime()
    resetActivityTimer()
  }
}

// 监听登录状态
watch(() => userStore.isLoggedIn, (isLoggedIn) => {
  if (!isLoggedIn) {
    router.push({ name: 'login' })
  } else {
    resetActivityTimer()
  }
}, { immediate: true })

// 监听路由变化
watch(route, (newRoute) => {
  if (userStore.isLoggedIn && newRoute) {
    activeTab.value = newRoute.path
    if (newRoute.meta.title) {
      addTab(newRoute)
    }
  }
}, { immediate: true })



// 新增登出处理
const handleLogout = async () => {
  isLoading.value = true
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
    router.push({ name: 'login' })
  } catch (error) {
    ElMessage.error('退出登录失败')
  } finally {
    isLoading.value = false
  }
}

// 添加标签页
const addTab = (route) => {
  const exists = tabs.value.some(tab => tab.path === route.path)
  if (!exists && route.meta.closable!== false) {
    tabs.value.push({
      path: route.path,
      meta: {
        title: route.meta.title,
        closable: route.meta.closable
      }
    })
  }
}

// 移除标签页
const removeTab = (targetPath) => {
  if (targetPath === '/home') return

  const index = tabs.value.findIndex(tab => tab.path === targetPath)
  if (index > -1) {
    tabs.value.splice(index, 1)
    if (targetPath === activeTab.value) {
      const newTab = tabs.value[index - 1] || tabs.value[0]
      router.push(newTab.path)
    }
  }
}

// 点击标签
const clickTab = (tab) => {
  router.push(tab.props.name)
}

// 处理标签操作
const handleTabCommand = (command) => {
  switch (command) {
    case 'closeCurrent':
      removeTab(activeTab.value)
      break;
    case 'closeOther':
      tabs.value = [
        tabs.value[0],
       ...tabs.value.filter(tab => tab.path === activeTab.value)
      ];
      break;
    case 'closeAll':
      tabs.value = [tabs.value[0]];
      router.push('/home');
      break;
  }
}




</script>

<style>
/* 全局CSS变量 */
:root {
  /* 默认值 - 深海蓝调主题 */
  --primary-color: #1a365d;
  --secondary-color: #c9a063;
  --accent-color: #4a6584;
  --background-color: #f5f2ea;
  --text-color: #333333;
  --header-bg: linear-gradient(135deg, #1a365d 0%, #2c5282 100%);
  --sidebar-bg: linear-gradient(180deg, #1a365d 0%, #2a4365 100%);
  --login-bg: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('/src/assets/atour-bg.jpg');
  

  
  /* 从主题变量派生的其他变量 */
  --primary-color-rgb: 26, 54, 93;
  --secondary-color-rgb: 201, 160, 99;
  
  /* Element Plus 组件主题 */
  --el-color-primary: var(--primary-color);
  --el-color-primary-light-3: rgba(var(--primary-color-rgb), 0.7);
  --el-color-primary-light-5: rgba(var(--primary-color-rgb), 0.5);
  --el-color-primary-light-7: rgba(var(--primary-color-rgb), 0.3);
  --el-color-primary-light-8: rgba(var(--primary-color-rgb), 0.2);
  --el-color-primary-light-9: rgba(var(--primary-color-rgb), 0.1);
  
  /* 文本颜色 */
  --el-text-color-primary: var(--text-color);
  --el-text-color-regular: #606266;
  
  /* 边框颜色 */
  --el-border-color-light: #e4e7ed;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
}

::-webkit-scrollbar-thumb {
  background: rgba(var(--primary-color-rgb), 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(var(--primary-color-rgb), 0.5);
}
</style>

<style scoped>
#app {
  height: 100vh;
  position: relative;
  overflow: hidden;
  color: var(--text-color);
}

/* 背景图层 */
.background-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: var(--background-color);
  z-index: -1;
  transition: background 0.5s ease;
}

.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* Header - 使用主题变量 */
.header-container {
  height: 60px;
  padding: 0 16px 0 5px;
  background: var(--header-bg);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  flex-shrink: 0;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: background 0.5s ease;
}

/* 覆盖Element Plus的el-header默认样式 */
.header-container :deep(.el-header) {
  padding: 0 !important;
  margin: 0 !important;
}



.content-container {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
}

/* 侧边栏 */
.sidebar {
  width: 200px;
  flex-shrink: 0;
  background: var(--sidebar-bg);
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
  transition: width 0.2s ease;
}

/* 收起状态 */
.sidebar.collapsed {
  width: 64px;
}



/* 桌面端布局 */
@media (min-width: 769px) {
  .content-container {
    display: flex;
  }
  
  .sidebar {
    flex-shrink: 0;
    width: 200px;
    transition: width 0.15s ease;
  }
  
  .sidebar.collapsed {
    width: 64px;
  }
  
  .main-content {
    flex: 1;
    min-width: 0;
  }
}



/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.95);
  min-width: 0;
  overflow: hidden;
  border-left: 1px solid rgba(0, 0, 0, 0.05);
}



.tabs-wrapper {
  padding: 16px 16px 8px;
  background: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  flex-shrink: 0;
  backdrop-filter: blur(4px);
}

.router-view-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.router-content {
  flex: 1;
  padding: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}



/* 标签页样式优化 */
:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: none;
}

:deep(.el-tabs__nav-wrap) {
  padding-right: 40px;
}

:deep(.el-tabs__item) {
  height: 36px;
  line-height: 36px;
  user-select: none;
  color: var(--text-color);
  transition: all 0.3s;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.7);
  margin-right: 8px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-tabs__item:hover) {
  background: rgba(255, 255, 255, 0.9);
  color: var(--primary-color);
}

:deep(.el-tabs__item.is-active) {
  color: var(--secondary-color);
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(var(--secondary-color-rgb), 0.3);
}

:deep(.el-tabs__content) {
  display: none;
}

:deep(.el-main) {
  padding: 0;
}

.more-btn {
  margin-left: 10px;
  font-size: 20px;
  cursor: pointer;
  transform: rotate(90deg);
  color: rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
}

.more-btn:hover {
  color: var(--secondary-color);
  transform: rotate(90deg) scale(1.1);
}




</style>